var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var session = require('express-session');

var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var loginRouter = require('./routes/login');
var logoutRouter = require('./routes/logout');
var productRouter = require('./routes/product');
var imagesRouter = require('./routes/images');
var distributionRouter = require('./routes/distribution');
var orderRouter = require('./routes/order');
var profitRouter = require('./routes/profit');
//小程序接口入口
var apiRouter = require('./routes/api/admin');
var app = express();

// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');

//设置跨域访问（设置在所有的请求前面即可）
app.all("*", function (req, res, next) {
  //设置允许跨域的域名，*代表允许任意域名跨域
  res.header("Access-Control-Allow-Origin", "*");
  //允许的header类型
  res.header("Access-Control-Allow-Headers", "Content-Type,Access-Token,token");
  //跨域允许的请求方式
  res.header("Access-Control-Allow-Methods", "DELETE,PUT,POST,GET,OPTIONS");
    next();
});

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
// app.use(express.static(path.join(__dirname)));
app.use(express.static(__dirname));
var bodyParser = require('body-parser');
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: false}));

// 配置session(需要配置在路由之前)
app.use(session({
      secret: '610481',
      resave: false,
      saveUninitialized: true,
      cookie: {
        maxAge: 1000*60*30
      },
      rolling:true
    })
);

const tokenObj = require('./util/jwt.js');
let myToken = new tokenObj();
// 验证token
app.use('/', function (req, res, next) {
  let urlArr = ['/login','/api'];
  let flag = urlArr.some(function(computer){
      return req.url.split('?')[0].includes(computer);
  });
  if(!flag){//需验证token
      let token = req.headers.token;
      myToken.checkToken(token,function(flag){
          if(!flag) return res.send({errCode:401,message:'登陆失效了'});
          next()
      });
  }else{
      next();
  }
});
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use('/login', loginRouter);
app.use('/logout', logoutRouter);
app.use('/product', productRouter);
app.use('/images', imagesRouter);
app.use('/distribution', distributionRouter);
app.use('/order', orderRouter);
app.use('/profit', profitRouter);
app.use('/api', apiRouter);
// catch 404 and forward to error handler
app.use(function(req, res, next) {
  next(createError(404));
});

// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};
  // render the error page
  res.status(err.status || 500);
  res.render('error');
});

module.exports = app;
